<template>
  <div class="query-form">
    <n-form
      ref="formRef"
      @change="onSearchClick"
      label-placement="left"
      :model="queryForm"
    >
      <n-collapse-transition :show="moreShow">
        <n-space>
          <slot v-if="moreShow" name="more" :queryForm="queryForm">
          </slot>
        </n-space>
      </n-collapse-transition>
      <n-space>
        <slot name="default" :queryForm="queryForm">
        </slot>
        <n-form-item>
          <n-space>
            <n-button type="primary" @click="onSearchClick">查询</n-button>
            <n-button type="default" @click="onReset">重置</n-button>
            <n-dropdown trigger="hover" :options="options" @select="handleSelect">
              <n-button>更多</n-button>
            </n-dropdown>

          </n-space>
        </n-form-item>
      </n-space>


    </n-form>
    <n-drawer v-model:show="active" :width="502" :placement="placement">

      <n-drawer-content title="历史查询记录">
        <n-button type="warning" @click="cleanQueryCache">
          清空历史查询
        </n-button>
        <n-list hoverable clickable>
          <n-list-item v-for="it in queryCache" @click="revertQueryForm(it.queryData)">
            <n-thing :title="it.time" content-style="margin-top: 0px;">
              <n-code
                :code="JSON.stringify(it.queryData,null,10)"
                language="javascript"
              />
            </n-thing>
          </n-list-item>
        </n-list>
      </n-drawer-content>
    </n-drawer>
    <n-drawer v-model:show="quickQueryActive" :width="502" :placement="placement">
      <n-drawer-content title="快捷查询">
        <n-list hoverable clickable>
          <n-list-item>
            <n-thing title="2022-09-01 00:00:00" content-style="margin-top: 10px;">
              <template #description>
                <n-space size="small" style="margin-top: 4px">
                  <n-tag :bordered="false" type="info" size="small">
                    暑夜
                  </n-tag>
                  <n-tag :bordered="false" type="info" size="small">
                    晚春
                  </n-tag>
                </n-space>
              </template>
              奋勇呀然后休息呀<br>
              完成你伟大的人生
            </n-thing>
          </n-list-item>
          <n-list-item>
            <n-thing title="他在时间门外" content-style="margin-top: 10px;">
              <template #description>
                <n-space size="small" style="margin-top: 4px">
                  <n-tag :bordered="false" type="info" size="small">
                    环形公路
                  </n-tag>
                  <n-tag :bordered="false" type="info" size="small">
                    潜水艇司机
                  </n-tag>
                </n-space>
              </template>
              最新的打印机<br>
              复制着彩色傀儡<br>
              早上好我的罐头先生<br>
              让他带你去被工厂敲击
            </n-thing>
          </n-list-item>
        </n-list>
      </n-drawer-content>
    </n-drawer>

  </div>
</template>

<script lang="ts">
import {
  DownOutlined,
  LeftOutlined,
  QuestionCircleOutlined,
  RightOutlined,
  UpOutlined
} from "@vicons/antd";
import { defineComponent, ref, unref, useSlots, watch } from "vue";
import { cloneDeep } from "lodash";
import { getCurTime, isEqual } from "@/components/QueryForm/util";
import md5 from "js-md5";


export default defineComponent({
  components: {
    RightOutlined,
    LeftOutlined,
    DownOutlined,
    UpOutlined,
    QuestionCircleOutlined,
    RightOutlined,
    LeftOutlined
  },
  props: {
    id: {
      type: [String],
      default: null
    },
    initQuery: {
      type: [Object],
      default: () => {
        return {};
      }
    },
    moreBtn: {
      type: [Boolean],
      default: () => {
        return true;
      }
    },
    resetBtn: {
      type: [Boolean],
      default: () => {
        return true;
      }
    },
    value: {
      type: [Object],
      default: () => {
        return {};
      }
    }
  },
  emits: ["submit", "reset", "register", "update:value", "update:modelValue"],
  setup(props, ctx) {
    const active = ref(false);
    const quickQueryActive = ref(false);
    const slotMore = !!useSlots().more;
    const { value, initQuery } = unref(props);
    const originQueryForm = cloneDeep(initQuery);
    console.log("历史参数", originQueryForm);
    const queryForm = ref(value);
    console.log(props.value);
    const moreShow = ref(false);
    let id: string = unref(props).id;
    if (id == null || id) {
      id = md5(window.location.href);
    }
    const unfoldToggle = async () => {
      moreShow.value = !moreShow.value;
    };
    const updateActive = () => {
      active.value = !active.value;
    };
    const saveQueryCache = () => {
      localStorage.setItem(`qct-${id}`, JSON.stringify(queryCache.value));
    };
    const readQueryCache = () => {
      const str = localStorage.getItem(`qct-${id}`);
      if (str) {
        return JSON.parse(str);
      }
      return [];
    };
    const lsCache = readQueryCache();
    const queryCache = ref<any>(lsCache);
    /**
     *
     * @param query
     */
    const addQueryCache = async (query: any) => {
      let data = {
        time: getCurTime(),
        queryData: { ...query }
      } as any;
      if (Object.keys(query).length == 0) {
        return;
      }
      if (queryCache.value.length > 1) {
        const { queryData } = queryCache.value[0];
        if (isEqual(query, queryData) || Object.keys(query).length == 0) {
          return;
        }
      }
      queryCache.value.unshift(data);
      if (queryCache.value.length > 10) {
        queryCache.value.splice(queryCache.value.length - 1, 1);
      }
      saveQueryCache();
    };

    const revertQueryForm = (query: any) => {
      active.value = false;
      queryForm.value = { ...query };
      onSearchClick(null);
    };
    const options = [
      // {
      //   label: "打开快捷查询",
      //   key: "quickQuery"
      // },
      // {
      //   label: "保存为快捷查询",
      //   key: "saveQuery"
      // },
      {
        label: "开启/关闭高级查询",
        key: "AdvancedQuery",
        disabled: !slotMore
      },
      {
        label: "历史查询记录",
        key: "HistoryQuery"
      }
    ];
    const onSearchClick = async (e) => {
      e && e.preventDefault();
      console.log("QueryForm参数:", queryForm.value);
      ctx.emit("update:modelValue", queryForm.value);
      ctx.emit("update:value", queryForm.value);
      ctx.emit("submit", queryForm.value);
      await addQueryCache(queryForm.value);
    };
    const onReset = (e) => {
      // e && e.preventDefault();
      //  console.log("原始参数", initQuery);
      //  console.log("原始参数2", queryForm.value);
      // // queryForm.value = { ...originQueryForm };
      // // console.log("原始参数3", queryForm.value);
      //  queryForm.value = reactive({ ...initQuery }) ;
      // // active.value = false;
      // console.log("原始参数3", queryForm.value);
      // active.value = true;
      //   queryForm.value = { ...initQuery };
      console.log("重置", initQuery);
      //   active.value = false;
      Object.keys(queryForm.value).forEach((key) => {
        queryForm.value[key] = initQuery[key] || null;
      });
      onSearchClick(null);

    };
    const cleanQueryCache = () => {
      queryCache.value = [];
      active.value = false;
    };
    const handleSelect = async (key: string) => {
      switch (key) {
        case "HistoryQuery": {
          active.value = true;
          break;
        }
        case "quickQuery": {
          quickQueryActive.value = true;
          break;
        }
        case "AdvancedQuery": {
          moreShow.value = !moreShow.value;
          break;
        }
      }
    };
    watch(() => props.modelValue, () => {
      console.log("QueryForm接收父组件参数:{}", props.modelValue);
      queryForm.value = props.modelValue;
    });
    watch(queryForm.value, async () => {
      await onSearchClick(null);
    });
    return {
      cleanQueryCache,
      handleSelect,
      revertQueryForm,
      quickQueryActive,
      slotMore,
      queryForm,
      queryCache,
      active,
      onReset,
      updateActive,
      moreShow,
      onSearchClick,
      unfoldToggle,
      options
    };
  }
});

</script>

<style scoped>
.query-form {
}
</style>
